package de.koller.million.grid.frame.plyManag;

import de.koller.million.grid.engine.PlayerContainer;
import de.koller.million.grid.engine.player.Player;
import java.util.*;
import javax.swing.ListModel;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;

public class PlayerList implements ListModel<Player> {
	
	private final PlayerManagerFrame node;
	private final Set<ListDataListener> listener = new HashSet<>();
	private PlayerContainer pcontainer = null;
	private final List<Player> players = new ArrayList<>();
	
	public PlayerList( PlayerManagerFrame node ) {
		this.node = node;
	}

	public void init() {
		pcontainer = node.groot.engine.playerContainer;
		notifyUpdate();
	}
	
	@Override
	public void addListDataListener( ListDataListener l ) {
		listener.add( l );
	}

	@Override
	public Player getElementAt( int index ) {
		if( players == null )
			return null;
		else
			return players.get( index );
	}

	@Override
	public int getSize() {
		if( players == null )
			return 0;
		else
			return players.size();
	}

	@Override
	public void removeListDataListener( ListDataListener l ) {
		listener.remove( l );
	}

	public void notifyUpdate() {
		if( pcontainer != null ) {
			players.clear();
			players.addAll( pcontainer.getPlayers() );
			Collections.sort( players, new Comparator<Player> () {
				@Override public int compare( Player o1, Player o2 ) {
					return o1.name.compareTo( o2.name );
				} } );
		}
		
		ListDataEvent event = new ListDataEvent( this, ListDataEvent.CONTENTS_CHANGED, 0, 1 );
		for( ListDataListener l : listener )
			l.contentsChanged( event );
	}
	
}
